﻿#region 命名空间

using System;
using System.IO;
using System.Web;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
using System.Web.UI.WebControls;
using WinnerCMS.Data;
using WinnerCMS.Model;
using WinnerCMS.Common;
using WinnerCMS.BLL.PageFactory.TagModule;

#endregion

namespace WinnerCMS.BLL
{
    /// <summary>
    /// 模板实体类
    /// </summary>
    public class TemplatesManage
    {
        private static readonly TemplatesDal MyDAL = new TemplatesDal();

        #region 添加

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Result Add(Template model)
        {
            Result res = new Result();
            string path = HttpContext.Current.Server.MapPath("~/Templates/" + model.TemplatePath.Trim());
            DirectoryInfo di = new DirectoryInfo(path);
            if (di.Exists == false)
            {
                res.Errors = "“模板目录”不存在！";
                return res;
            }
            path =
                HttpContext.Current.Server.MapPath("~/Templates/" + model.TemplatePath.Trim() + @"/" +
                                                   model.Style.Trim());
            di = new DirectoryInfo(path);
            if (di.Exists == false)
            {
                res.Errors = "“模板CSS目录”不存在！";
                return res;
            }


            if (model.TemplateName.Length == 0)
            {
                res.Errors = "“模板名称”不能为空！";
                return res;
            }
            if (model.TemplatePath.Length == 0)
            {
                res.Errors = "“模板目录”不能为空！";
                return res;
            }

            if (string.IsNullOrEmpty(model.Id))
            {
                MyDAL.Add(model);
            }
            else
            {
                MyDAL.Edit(model);
            }
            ClearCache();

            return res;
        }

        #endregion

        #region 删除

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="UpdatePanel1"></param>
        public void Delete(string ID, UpdatePanel UpdatePanel1)
        {
            MyDAL.Delete(ID);
            ClearCache();
            MsgBox.Message("操作成功！", UpdatePanel1);
        }

        #endregion

        #region 应用模板

        /// <summary>
        /// 应用模板
        /// </summary>
        /// <param name="ID"></param>
        public void UsedIt(string ID, UpdatePanel UpdatePanel1)
        {
            Template model = MyDAL.GetInfo(ID);

            if (model != null)
            {
                string strDir = HttpContext.Current.Server.MapPath("~/Templates/" + model.TemplatePath);
                DirectoryInfo dirInfo = new DirectoryInfo(strDir);
                if (dirInfo.Exists == false)
                {
                    MsgBox.Message("模板不存在！", UpdatePanel1);

                    return;
                }

                MyDAL.UsedIt(ID);


                CopyDirectory(HttpServer.MapPath("~\\Templates\\" + model.TemplatePath), HttpServer.MapPath("~\\"));
                ClearCache();

                CacheStorager.CMSCaches.Context.FlushAll();
            }
            else
            {
                MsgBox.Message("模板不存在！", UpdatePanel1);
                return;
            }

            MsgBox.Message("操作成功！", UpdatePanel1);
        }


        /// <summary> 
        /// 复制目录及其文件往新目录
        /// </summary> 
        /// <param name="src">源目录</param> 
        /// <param name="dest">目标目录</param> 
        private static void CopyDirectory(string src, string dest)
        {
            DirectoryInfo di = new DirectoryInfo(src);
            foreach (FileSystemInfo fsi in di.GetFileSystemInfos())
            {
                string destName = Path.Combine(dest, fsi.Name);

                if (fsi is FileInfo)
                {
                    if (fsi.Name.Equals("vssver2.scc", StringComparison.CurrentCultureIgnoreCase))
                    {
                        continue;
                    }
                    if (fsi.Name.Equals("info.config", StringComparison.CurrentCultureIgnoreCase))
                    {
                        continue;
                    }
                    if (fsi.Name.Equals("Bundle.config", StringComparison.CurrentCultureIgnoreCase))
                    {
                        continue;
                    }
                    if (fsi.Extension.Equals(".cs", StringComparison.CurrentCultureIgnoreCase))
                    {
                        continue;
                    }

                    if (fsi.Extension.Equals(".aspx", StringComparison.CurrentCultureIgnoreCase) ||
                        fsi.Extension.Equals(".inc", StringComparison.CurrentCultureIgnoreCase))
                    {
                        using (StreamReader sr = new StreamReader(fsi.FullName))
                        {
                            using (StreamWriter objWriter = new StreamWriter(destName, false))
                            {
                                StringBuilder winner = new StringBuilder(sr.ReadToEnd());
                                PageFactory.Pages.UDT.Translate(winner);
                                TagEngine.ReplaceM(winner, 0);

                                objWriter.Write(HTML.Compress(winner.ToString()));
                                //objWriter.Write(winner.ToString());

                                objWriter.Flush();
                            }
                        }
                    }
                    else
                    {
                        FileInfo fi = new FileInfo(fsi.FullName)
                        {
                            Attributes = FileAttributes.Normal
                        };
                        fi.CopyTo(destName, true);
                    }
                }
                else
                {
                    if (fsi.Name == "Scripts" || fsi.Name == "Style")
                    {
                        continue;
                    }
                    Directory.CreateDirectory(destName);
                    CopyDirectory(fsi.FullName, destName);
                }
            }
        }

        #endregion

        #region 加载数据

        /// <summary>
        /// 加载数据
        /// </summary>
        public Template GetInfo(string id)
        {
            return MyDAL.GetInfo(id);
        }

        #endregion

        #region 清空缓存

        private void ClearCache()
        {
            _getuseing = null;
        }

        #endregion

        #region 读取模板数据

        private static Template _getuseing;
        private static readonly object Lockobj = new object();

        /// <summary>
        /// 读取模板数据
        /// </summary>
        public static Template GetUseing
        {
            get
            {
                if (_getuseing == null)
                {
                    lock (Lockobj)
                    {
                        if (_getuseing == null)
                        {
                            _getuseing = MyDAL.GetUseing().Result;
                        }
                    }
                }
                return _getuseing;
            }
        }

        #endregion

        /// <summary>
        /// 绑定数据
        /// </summary>
        /// <returns></returns>
        public IList<Template> BindList()
        {
            return MyDAL.BindList();
        }
    }
}